package com.ghy.component;


import cn.hutool.json.JSONUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.ghy.result.Result;

/**
 * @author GaoHeYang
 */
@RestControllerAdvice(basePackages = "com.ghy.controller")
public class ResultAdvice implements ResponseBodyAdvice<Object>{

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass){
        //放行到beforeBodyWrite（）方法
        return true;
    }
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter,
                                  MediaType mediaType, Class aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        //若Jackson使用字符串转换器，使用JsON封装一下再直接返回字符串，避免爆发转换异常
        if (aClass == StringHttpMessageConverter.class) {
            return JSONUtil.toJsonStr(o);
        }

        //若返回值已经是Result类型则直接返回
        if (o instanceof Result) {
            return o;
        }

        //统一将Controller的返回值封装为Result类型
        return new Result<>(o);
    }
}
